<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline"
      v-hasPermi="['sa:report:query']">
      <el-form-item label="创建人" prop="createBy">
        <el-input v-model.trim="queryParams.createBy" size="small" clearable :minlength="100"
          placeholder="请输入创建人"></el-input>
      </el-form-item>
      <el-form-item label="日期" prop="projectDate">
        <el-date-picker v-model="projectDate" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="small">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['sa:report:add']"
            @click="openDialog(null)">增加</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table ref="tableRef" :data="tableData" v-loading="loading" highlight-current-row max-height="680"
      v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
      <el-table-column type="index" width="50" align="center" label="序号">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column property="province" label="省份" align="center" width="120" />
      <el-table-column property="finishRate" label="年度目标完成率" align="center">
        <template slot-scope="scope">
          <div v-html="scope.row.finishRate.replace(/\n/g, '<br/>')"></div>
        </template>
      </el-table-column>
      <el-table-column property="developSchedule" label="重点客户与重点项目发展进度" align="center" min-width="400">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content" v-html="scope.row.developSchedule.replace(/\n/g, '<br/>')" class=" cus_text"></div>
            <div class="oneLine">{{scope.row.developSchedule}}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column property="nextWork" label="下阶段重要工作" align="center" width="200">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content" v-html="scope.row.nextWork.replace(/\n/g, '<br/>')" class=" cus_text"></div>
            <div class="oneLine">{{scope.row.nextWork}}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column property="refundSchedule" label="已/待验收项目回款情况" align="center" width="240">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content" v-html="scope.row.refundSchedule.replace(/\n/g, '<br/>')" class=" cus_text"></div>
            <div class="oneLine">{{scope.row.refundSchedule}}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column property="teamManagement" label="团队建设与管理" align="center">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content" v-html="scope.row.teamManagement.replace(/\n/g, '<br/>')" class=" cus_text"></div>
            <div class="oneLine">{{scope.row.teamManagement}}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column property="resolutionDiscussed" label="待讨论决议事项" align="center">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content" v-html="scope.row.resolutionDiscussed.replace(/\n/g, '<br/>')" class=" cus_text"></div>
            <div class="oneLine">{{scope.row.resolutionDiscussed}}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column property="remark" label="备注" align="center" />
      <el-table-column property="createBy" label="创建人" align="center" width="80" />
      <el-table-column property="createTime" label="创建时间" align="center" sortable />
      <el-table-column label="操作" align="center"
        v-if="$auth.hasPermi('sa:report:edit') || $auth.hasPermi('sa:report:remove') || $auth.hasPermi('sa:report:view')">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-view" v-hasPermi="['sa:report:view']"
                     @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['sa:report:edit']"
            @click="openDialog(scope.row)">修改</el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
            @confirm="deleteHandler(scope.row)">
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['sa:report:remove']"
              type="text" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="dialogTitle === 1 ? '新增' : '修改'" :visible.sync="dialogVisible" width="700px"
      :close-on-click-modal="false" :fullscreen="device == 'mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" class="demo-form"
        :label-position="device == 'mobile' ? 'top' : 'right'">
        <el-row :gutter="20">
          <el-col :span="device == 'mobile' ? 24 : 12">
            <el-form-item label="省份" prop="province">
              <el-select v-model="form.province" clearable filterable placeholder="请选择省份" style="width: 100%;">
                <el-option v-for="item in provinceList" :key="item.code" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="device == 'mobile' ? 24 : 12">
            <el-form-item label="年度目标完成率" prop="finishRate">
              <el-input v-model="form.finishRate" type="textarea" :maxlength="1000" placeholder="年度目标完成率"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device == 'mobile' ? 24 : 12">
            <el-form-item label="重点客户与重点项目发展进度" prop="developSchedule">
              <el-input v-model="form.developSchedule" type="textarea" :maxlength="1000" placeholder="重点项目发展进度"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
          <el-col :span="device == 'mobile' ? 24 : 12">
            <el-form-item label="下阶段重要工作" prop="nextWork">
              <el-input v-model="form.nextWork" type="textarea" :maxlength="1000" placeholder="下阶段重要工作"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device == 'mobile' ? 24 : 12">
            <el-form-item label="已/待验收项目回款情况" prop="refundSchedule">
              <el-input v-model="form.refundSchedule" type="textarea" :maxlength="1000" placeholder="已/待验收项目回款情况"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
          <el-col :span="device == 'mobile' ? 24 : 12">
            <el-form-item label="团队建设与管理" prop="teamManagement">
              <el-input v-model="form.teamManagement" type="textarea" :maxlength="1000" placeholder="团队建设与管理"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="device == 'mobile' ? 24 : 12">
            <el-form-item label="待讨论决议事项" prop="resolutionDiscussed">
              <el-input v-model="form.resolutionDiscussed" type="textarea" :maxlength="1000" placeholder="待讨论决议事项"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
          <el-col :span="device == 'mobile' ? 24 : 12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :maxlength="250" placeholder="请输入备注"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addDataApi, deleteDataApi, getDataListApi, updateDataApi } from "@/api/crm/sa/report";
import { getDataListApi as getAllProjectListApi } from "@/api/crm/md/project";
import ProvinceData from '@/views/crm/data/province.json'
import { getUserProfile } from "@/api/system/user";
import { mapGetters } from 'vuex'

export default {
  name: 'ReportView',
  dicts: ['sys_project_schedule'],
  data() {
    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 项目日期
      projectDate: [],
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        competitionSchedule: "", // 重点客户(贷款申报)与竞赛(新客户)进度
        createBy: "", // 创建人
        createTime: "", // 创建时间
        developSchedule: "", // 重点项目发展进度
        // endDate: "", // 结束时间
        province: "", // 省份
        finishRate: "", // 年度目标完成率
        id: null,
        nextWork: "", // 下阶段重要工作
        refundSchedule: "", // 已/待验收项目回款情况
        remark: "", // 备注
        resolutionDiscussed: "", // 待讨论决议事项
        // startDate: "", // 开始时间
        teamManagement: "", // 团队建设与管理
        updateBy: "",
        updateTime: ""
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        province: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
        competitionSchedule: [
          { required: true, message: '请输入重点客户(贷款申报)与竞赛(新客户)进度', trigger: 'blur' }
        ], // 重点客户(贷款申报)与竞赛(新客户)进度
        developSchedule: [
          { required: true, message: '请输入重点项目发展进度', trigger: 'blur' }
        ], // 重点项目发展进度
        // endDate: [
        //   { required: true, message: '请选择结束日期', trigger: 'blur' }
        // ],
        finishRate: [
          { required: true, message: '请输入年度目标完成率', trigger: 'blur' }
        ], // 年度目标完成率
        nextWork: [
          { required: true, message: '请输入下阶段重要工作', trigger: 'blur' }
        ], // 下阶段重要工作
        refundSchedule: [
          { required: true, message: '请输入已/待验收项目回款情况', trigger: 'blur' }
        ], // 已/待验收项目回款情况
        // resolutionDiscussed: [
        //   { required: true, message: '请输入待讨论决议事项', trigger: 'blur' }
        // ],
        // 待讨论决议事项
        // startDate: [
        //   { required: true, message: '请选择开始日期', trigger: 'blur' }
        // ],
        // teamManagement: [
        //   { required: true, message: '请输入团队建设与管理', trigger: 'blur' }
        // ],
        // 团队建设与管理
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        createBy: "", // 学校名 *
        province: "", // 省份 *
        startDate: "",
        endDate: "",
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 项目数据
      projectList: [],
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ])
  },
  watch: {
    projectDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.isImportant': {
      handler(newV) {
        if (newV !== 1) {
          this.form.basis = null
        }
      }
    },
  },
  created() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    this.getAllProjectList()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 查看周报详细信息
    handleView(row) {
      this.$router.push({ name: 'ReportDetail', query: { report: row.id } })
    },
    // 查询全部项目
    getAllProjectList() {
      getAllProjectListApi().then((res) => {
        this.projectList = res.rows ?? []
      })
    },
    // 选择重点的回调
    changePropertyHandler(val) {
      if (val === 0) {
        this.form.basis = null
      }
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        this.tableData = res.rows
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = { ...row }
        this.dialogTitle = 2
      } else {
        if (this.formId) {
          this.form = { ...this.$options.data().form }
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/newspaper/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `newspaper_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      if (this.form.isImportant === 1 && !(this.form.basis)) {
        this.$notify({
          title: '警告',
          message: '请选择重点依据',
          type: 'warning'
        });
        return false
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        finishRate: this.form.finishRate.trim(),
        developSchedule: this.form.developSchedule.trim(),
        nextWork: this.form.nextWork.trim(),
        refundSchedule: this.form.refundSchedule.trim(),
        teamManagement: this.form.teamManagement.trim(),
        resolutionDiscussed: this.form.resolutionDiscussed.trim(),
        deptId: this.user.deptId,
        userId: this.user.userId,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
        this.$refs['formRef'].resetFields();
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        finishRate: this.form.finishRate.trim(),
        developSchedule: this.form.developSchedule.trim(),
        nextWork: this.form.nextWork.trim(),
        refundSchedule: this.form.refundSchedule.trim(),
        teamManagement: this.form.teamManagement.trim(),
        resolutionDiscussed: this.form.resolutionDiscussed.trim(),
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.projectDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>

<style scoped lang="scss">
.oneLine {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.cus_text{
  font-size: larger;
  margin: 10px;
}
</style>
